<?php
class AppController extends Controller {

	/**
	 * components
	 *
	 * Array of components to load for every controller in the application
	 *
	 * @var $components array
	 * @access public
	 */
	var $components = array('Cookie','Auth', 'Redirect','Menu','Search','Browser','AuthExtension');

	var $helpers = array('Html', 'Form', 'Javascript','Menu');

	var $uses = array('Whoonline','Analytic');

	/**
	 * beforeFilter
	 *
	 * Application hook which runs prior to each controller action
	 *
	 * @access public
	 */
	function beforeFilter(){


		//Set Redirect false for AuthExtension
		$this->Auth->autoRedirect = false;

		$this->__setSettings();
		//Check for the layout
		if (strpos($this->action, 'admin_') !== false) {
			$this->layout = 'admin_index';
		}

		//
		//$this->layout = 'admin_dashboard';
		//Override default fields used by Auth component
		$this->Auth->fields = array('username'=>'user_name','password'=>'password');
		//Set application wide actions which do not require authentication
		//$this->Auth->allow('display');//IMPORTANT for CakePHP 1.2 final release change this to $this->Auth->allow(array('display'));
		$this->Auth->allow(array('display'));
		//Set the default redirect for users who logout
		$this->Auth->logoutRedirect = '/users/login';


		$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
		//Set the default redirect for users who login
		$this->Auth->loginRedirect = '/admin';


		//Extend auth component to include authorisation via isAuthorized action
		$this->Auth->authorize = 'controller';
		//Restrict access to only users with an active account
		$this->Auth->userScope = array('User.active = 1');



		//Pass auth component data over to view files
		$this->set('Auth',$this->Auth->user());

		//Set Limit for pagination
		$this->paginate = array('limit' => 5);
		$this->__checkOnlineStats();

	
		// In AppController (or single controller if only needed once) add these lines to beforeFilter :

		if (sizeof($this->uses) && $this->{$this->modelClass}->Behaviors->attached('Logable')) {
			$this->{$this->modelClass}->setUserData($this->Session->read('Auth'));
		}
		
		parent::beforeFilter();
	}

	function afterFilter(){
		$this->__checkAnalytics();
	}


	/**
	 * beforeRender
	 *
	 * Application hook which runs after each action but, before the view file is
	 * rendered
	 *
	 * @access public
	 */
	function beforeRender(){

		//If we have an authorised user logged then pass over an array of controllers
		//to which they have index action permission
		if($this->Auth->user()){
			$this->set('currentUserName',$this->Auth->user('user_name'));
			$controllerList = Configure::listObjects('controller');
			$permittedControllers = array();
			foreach($controllerList as $controllerItem){
				if($controllerItem <> 'App'){
					if($this->__permitted($controllerItem,'index')){
						$permittedControllers[] = $controllerItem;
					}
				}
			}
		}
		$this->set(compact('permittedControllers'));
		$this->__setGeneralSettings();

	}

	/**
	 * isAuthorized
	 *
	 * Called by Auth component for establishing whether the current authenticated
	 * user has authorization to access the current controller:action
	 *
	 * @return true if authorised/false if not authorized
	 * @access public
	 */
	function isAuthorized(){
		return $this->__permitted($this->name,$this->action);
	}

	/**
	 * __permitted
	 *
	 * Helper function returns true if the currently authenticated user has permission
	 * to access the controller:action specified by $controllerName:$actionName
	 * @return
	 * @param $controllerName Object
	 * @param $actionName Object
	 */
	function __permitted($controllerName,$actionName){

		//Ensure checks are all made lower case
		$controllerName = low($controllerName);
		$actionName = low($actionName);
		//If permissions have not been cached to session...
		if(!$this->Session->check('Permissions')){
			//...then build permissions array and cache it
			$permissions = array();
			//everyone gets permission to logout
			$permissions[]='users:logout';
			//Import the User Model so we can build up the permission cache
			App::import('Model', 'User');
			$thisUser = new User;
			//Now bring in the current users full record along with groups
			$thisGroups = $thisUser->find(array('User.id'=>$this->Auth->user('id')));
			$thisGroups = $thisGroups['Group'];
			foreach($thisGroups as $thisGroup){
				$thisPermissions = $thisUser->Group->find(array('Group.id'=>$thisGroup['id']));
				$thisPermissions = $thisPermissions['Permission'];
				foreach($thisPermissions as $thisPermission){
					$permissions[]=$thisPermission['name'];
				}
			}
			//write the permissions array to session
			$this->Session->write('Permissions',$permissions);
		}else{
			//...they have been cached already, so retrieve them
			$permissions = $this->Session->read('Permissions');

		}
		//Now iterate through permissions for a positive match
		foreach($permissions as $permission){
			if($permission == '*'){
				return true;//Super Admin Bypass Found
			}
			if($permission == $controllerName.':*'){
				return true;//Controller Wide Bypass Found
			}
			if($permission == $controllerName.':'.$actionName){
				return true;//Specific permission found
			}
		}
		return false;
	}

	function __setSettings() {
		$Setting  = ClassRegistry::init('Setting');
		$settings = $Setting->find('all');
		foreach($settings as $_setting) {
			if ($_setting['Setting']['value']!==null) {
				Configure::write('Settings.'.$_setting['Setting']['category'].'.'.$_setting['Setting']['setting'], $_setting['Setting']['value']);
			}
		}
		// you can now use the following anywhere in your app
		// $settings = Configure::read('Settings.app'); debug($settings)
	}

	// Set Menu and General Info Setting for Website
	function __setGeneralSettings(){
		$this->set('nav_menu', $this->Menu->getMenu());
		$this->set('website_name',Configure::read('Settings.app.name'));
		if ((strpos($this->action, 'admin_index') !== false) || (strpos($this->action, 'admin_search') !== false)) {
			$this->set('checkall_script',true);
		}
	}

	function redirectDataSearch(){
		// the page we will redirect to
		$url['controller'] = $this->controller;
		$url['action'] = 'search';

		// build a URL will all the search elements in it
		// the resulting URL will be
		// example.com/cake/posts/index/Search.keywords:mykeyword/Search.tag_id:3
		foreach ($this->data as $k=>$v){
			foreach ($v as $kk=>$vv){
				$url[$k.'.'.$kk]=$vv;
			}
		}
		// redirect the user to the url
		$this->redirect($url, null, true);
	}

	function doSearch($passedArgs){
		$conditions = array();
		$singularName = ucfirst(Inflector::humanize(Inflector::underscore(Inflector::singularize($this->controller))));
		if (!empty($passedArgs))
		{
			if (isset($passedArgs['Search.'.name]))
			{
				$conditions[][$singularName.".name LIKE"] = "%{$passedArgs['Search.name']}%";
				$this->data['Search']['name'] = $passedArgs['Search.name'];
			}
			$this->paginate = array('limit' => '1', 'order' => $singularName.'.created DESC');
			$result=$this->paginate($singularName, $conditions);

			if(count($result)>0){
				$this->set(strtolower($this->controller), $result);
			} else {
				$this->Redirect->flashWarning('Data not found');
			}
		}
	}



	// Function to check User Online
	function __checkOnlineStats()
	{
			

		if(!$this->Session->check('online')){
			$this->data['Whoonline']['controller'] = $this->params["controller"];
			$this->data['Whoonline']['action'] = $this->params["action"];
			$this->data['Whoonline']['browser'] = $this->Browser->get_browser($_SERVER['HTTP_USER_AGENT']);
			$this->data['Whoonline']['os'] = $this->Browser->get_os($_SERVER['HTTP_USER_AGENT']);
			$this->data['Whoonline']['ip_address'] = $_SERVER['REMOTE_ADDR'];
			if(isset($_SERVER['HTTP_REFERER']))
			$this->data['Whoonline']['refurl'] = $_SERVER['HTTP_REFERER'];
			else
			$this->data['Whoonline']['refurl'] = "Direct";
			$this->data['Whoonline']['activity'] = time();
			$this->data['Whoonline']['id'] = $this->Session->id();

			$this->Whoonline->save($this->data);
			$this->Session->write('online',1);

		} else {
			$this->data['Whoonline']['id'] = $this->Session->id();
			$this->data['Whoonline']['activity'] = time();
			$this->data['Whoonline']['controller'] = $this->params["controller"];
			$this->data['Whoonline']['action'] = $this->params["action"];
			$this->data['Whoonline']['browser'] = $this->Browser->get_browser($_SERVER['HTTP_USER_AGENT']);
			$this->data['Whoonline']['os'] = $this->Browser->get_os($_SERVER['HTTP_USER_AGENT']);
			$this->data['Whoonline']['ip_address'] = $_SERVER['REMOTE_ADDR'];
			if(isset($_SERVER['HTTP_REFERER']))
			$this->data['Whoonline']['refurl'] = $_SERVER['HTTP_REFERER'];
			else
			$this->data['Whoonline']['refurl'] = "Direct";
			if (($this->Auth->user('user_name')!="")){
				$this->data['Whoonline']['member'] = 'y';
				$this->data['Whoonline']['user_id'] = $this->Auth->user('id');
				$this->data['Whoonline']['user_name'] = $this->Auth->user('user_name');
			} else {
				$this->data['Whoonline']['user_id'] = '0';
				$this->data['Whoonline']['user_name'] = 'Guest';
				$this->data['Whoonline']['member'] = 'n';
			}
			$this->Whoonline->save($this->data);
		}

		/*
		 if($this->Session->check('online')){
			$this->data['Whoonline']['id'] = 	$this->Session->id();
			$this->data['Whoonline']['activity'] = time();
			$this->Whoonline->save($this->data);
			}
			*/
			
		if (date('H') == 00) {
			$time_limit = time() - 7200;
			$this->Whoonline->deleteAll(array('activity < ' => $time_limit), false);
		}
			
		// The following line is a fix by Termnial13 (thanks). It removes tracker stuffs from $this->data as it was causing some users issues.
		unset($this->data['Whoonline']);

	}

	// Function to get Data for Analytics
	function __checkAnalytics()
	{
		if(!$this->Session->check('analytic')){
			$this->data['Analytic']['ip_address'] = $_SERVER['REMOTE_ADDR'];
			$this->data['Analytic']['pageviews'] = '1';
			$this->Analytic->save($this->data);
			$this->Session->write('analytic',$this->Analytic->id);
		} else {
				
			$this->Analytic->id = (int)$this->Session->read('analytic');
			$this->data['Analytic']['pageviews'] = (int)$this->Analytic->field('pageviews') + 1;
			$this->Analytic->save($this->data);
		}
		// The following line is a fix by Termnial13 (thanks). It removes tracker stuffs from $this->data as it was causing some users issues.
		unset($this->data['Analytic']);

	}

}
